
use iced::{event, window::{self, open, Id, Position}, Color, Element, Event, Size, Subscription, Task};
use iced::{alignment, widget::{ container, text::Alignment, text_input::{self}, Column, Container, TextInput}, Background, Border, Font, Length::{self}, Shadow};
use iced::{futures::{channel::mpsc, SinkExt, StreamExt}, stream};
use rdev::{listen, EventType, Key};
pub struct MomentoIced {
    text: String,
    popup_id: Option<Id>
}

#[derive(Debug, Clone)]
pub enum MainMessage {
    OpenFiiloutWindow,
    InputChanged(String),
    WindowClosed(Id),
    Submit,
    EventOccurred(iced::Event),
}

impl MomentoIced {
    pub fn new() -> (Self, Task<MainMessage>) {
        (
            Self {
                text: String::new(),
                popup_id: None, 
            },
            Task::none()
        )
    }

    pub fn title(&self, window: Id) -> String {
        println!("{:?}", window);
        "".to_string()
    }
    pub fn update(&mut self, message: MainMessage) -> Task<MainMessage> {
        match message {
            MainMessage::OpenFiiloutWindow => {
                 if let Some(id) = self.popup_id {
                    // 窗口已存在：还原并聚焦
                    return window::minimize(id, false)
                        .chain(window::gain_focus(id));
                 } else {
                    let (id, task) = open(window::Settings {
                        size: Size {
                            width: 700.0,
                            height: 80.0,
                        },
                        decorations: false,
                        transparent: true,
                        position: Position::SpecificWith(|win,screen| {
                                iced::Point {
                                    x: (screen.width - win.width) / 2.0,  // 假设已获取屏幕宽度
                                    y: screen.height / 3.0   // 假设已获取屏幕高度
                                }
                        }), // 新增这行关键设置
                        
                        #[cfg(target_os = "macos")]
                        platform_specific: PlatformSpecific {
                            title_hidden: true,
                            titlebar_transparent: true,
                            fullsize_content_view: true,
                        },
                        #[cfg(target_os = "linux")]
                        platform_specific: PlatformSpecific {
                            application_id: String::from("Capter"),
                            override_redirect: true,
                        },
                        ..Default::default()
                    });
                    // 记录窗口 id，下次就能用 show 而不是再 open
                    self.popup_id = Some(id);
                    return task.discard().chain(window::gain_focus(id));
                 }

            },
            MainMessage::WindowClosed(id) => {
                if Some(id) == self.popup_id {
                    self.popup_id = None;
                }
                return window::close(id);
            },
            MainMessage::InputChanged(x) => {
                        self.text = x;
            },
            MainMessage::Submit => {
                        println!("{}", self.text);
                        self.text = "".to_string();
            },
            MainMessage::EventOccurred(event) => {
                // 这里可以根据需要拓展更多事件监听
                if let Event::Window(window::Event::Unfocused) = event {
                    if let Some(id) = self.popup_id {
                        // 鼠标移出时最小化（隐藏）
                        return window::minimize(id, true);
                    }
                } else {
                    return Task::none();
                }
            }
            _ => {
                println!("00000");
            }
        }
        Task::none()
    }


    pub fn view(&self, id: Id) -> Element<MainMessage> {
        let editor = Column::new()
        .push(
            Container::new(
                TextInput::new("请输入...", &self.text)
                    .on_input(MainMessage::InputChanged)
                    .on_submit(MainMessage::Submit)
                    .size(20.0)
                    .font(Font::default())
                    .style(|_theme, _status| {
                        text_input::Style {
                            background: Color::TRANSPARENT.into(), // 透明背景
                            border: Border::default(), // 隐藏原生边框
                            icon: Color::BLACK,
                            placeholder: Color::WHITE,
                            value: Color::WHITE,
                            selection: Color::BLACK,
                        }
                    })
                    .width(Length::Fill)
            )
            .style(|_theme| {
                container::Style {
                    background: Some(Background::Color(Color { r: 0.0, g: 0.0, b: 0.0, a: 0.8 })),
                    border: Border {
                        radius: 80.0.into(), // 容器圆角
                        width: 1.0,
                        color: Color::TRANSPARENT,
                    },
                    text_color: Some(Color::default()),
                    shadow: Shadow::default(),
                    snap: true,
                }
            })
            .align_x(Alignment::Center)
            .align_y(alignment::Vertical::Center)
            .padding(10) // 增加内边距
            .width(Length::Fill)
            .height(Length::Fill)
        )
        .height(Length::Fill)
        .width(Length::Fill);
        editor.into()
    }

    pub fn subscription(&self) -> Subscription<MainMessage> {
        let window_events_occurred = event::listen().map(MainMessage::EventOccurred);
        let global_key_listener = Subscription::run(|| {
            stream::channel(1, async|mut output| {
                let (mut sender, mut receiver) = mpsc::channel(1);
                std::thread::spawn(move || {
                    let _ = listen(move |event| {
                        match event.event_type {
                        EventType::KeyPress(_key) =>{
                            let _ = sender.try_send(event);
                        },
                        EventType::KeyRelease(_key) => {
                            let _ = sender.try_send(event);
                        },
                        _ => (),
                        }
                        
                    });
                });

                let mut ctrl_pressed = false;
                let mut shift_pressed = false;

                loop {
                    let event = receiver.select_next_some().await;
                    println!("{:?}", event);
                    match event.event_type {
                        EventType::KeyPress(key) => match key {
                            Key::ControlLeft => ctrl_pressed = true,
                            Key::ShiftLeft | Key::ShiftRight => shift_pressed = true,
                            Key::KeyQ if ctrl_pressed && shift_pressed => {
                                let _ = output.send(MainMessage::OpenFiiloutWindow).await;
                            }
                            _ => (),
                        },
                        EventType::KeyRelease(key) => match key {
                            Key::ControlLeft => {
                                ctrl_pressed = false;
                            }
                            Key::ShiftLeft | Key::ShiftRight => {
                                shift_pressed = false;
                            }
                            _ => (),
                        },
                        _ => (),
                    }
                }
            })
        });
        let list = vec![
            window_events_occurred,
            global_key_listener,
        ];
        Subscription::batch(list)
    }

}

